var express = require('express');
var app = express();
var createError = require('http-errors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var fs = require('fs')
var formidable = require('formidable')

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/mall')
var db = mongoose.connection

/**
  * 连接成功
  */
db.on('connected', function () {
  console.log('db connect succeed!');
});

/**
 * 连接异常
 */
db.on('error', function (err) {
  console.log('db connection error: ' + err);
});

/**
 * 连接断开
 */
db.on('disconnected', function () {
  console.log('db connection disconnected');
});

/**
 * 打开成功
 */
db.once('open', function () {
  console.log('数据库test_nodeVue连接成功')
  // 初始化数据库
  initData();
})


const initData = function () {
  
}


var UserSchema = new mongoose.Schema({
  name: { type: String },
  price: { type: String }
})

var User = mongoose.model('User', UserSchema);


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/views', express.static('views'));



app.get('/user', function (req, res) {
  User.find(function (err, doc) {
    if (err) {
      console.log(err)
    } else {
      res.send(doc)
    }
  })
});

app.get('/remove', function (req, res, next) {
  User.remove({ 'name': 'Jin' }, function (err, p) {
    if (err) {
      console.log(err)
    } else {
      res.send('删除成功')
    }
  })
});

app.get('/', function (req, res) {
  res.send('GET')
});

app.post('/addProduct',function(req,res,next){
  var form = new formidable.IncomingForm();
  console.log("about to parse");
  form.parse(req, function(error, fields, files) {
      console.log("parsing done");
      console.log(files.upload.path);
      fs.writeFileSync("public/images/image1.png", fs.readFileSync(files.upload.path));
      res.redirect("/views/uploadProduct.html") ;
  });

});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
